package com.tsq.weixin.provider.manage;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.ImmutableMap;
import com.tsq.common.model.ResponseData;
import com.tsq.weixin.api.form.MaterialFileDeleteForm;
import com.tsq.weixin.provider.service.WxAssetsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.material.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

import static me.chanjar.weixin.mp.enums.WxMpApiUrl.MassMessage.MESSAGE_MASS_SENDALL_URL;

/**
 * 微信公众号素材管理
 * 参考官方文档：https://developers.weixin.qq.com/doc/offiaccount/Asset_Management/New_temporary_materials.html
 * 参考WxJava开发文档：https://github.com/Wechat-Group/WxJava/wiki/MP_永久素材管理
 */
@RestController
@RequestMapping("/manage/wxAssets")
@Api(value = "WxAssetsManageController", tags = {"微信公众号素材管理"})
public class WxAssetsManageController {
    @Autowired
    WxAssetsService wxAssetsService;
    @Autowired
    private WxMpService wxMpService;

    @GetMapping("/materialCount")
    @ApiOperation(value = "获取素材总数", notes = "获取素材总数")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "appid", value = "appid", dataType = "String", paramType = "head")
    })
    public ResponseData<WxMpMaterialCountResult> materialCount(@RequestHeader String appid) throws WxErrorException {

        wxMpService.switchoverTo(appid);
        WxMpMaterialCountResult res = wxAssetsService.materialCount();
        return ResponseData.success(res);
    }

    @GetMapping("/materialFileBatchGet")
    @ApiOperation(value = "根据类别分页获取非图文素材列表", notes = "根据类别分页获取非图文素材列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "appid", value = "appid", dataType = "String", paramType = "head"),
            @ApiImplicitParam(name = "type", value = "类别，默认是image", dataType = "String", paramType = "param"),
            @ApiImplicitParam(name = "page", value = "页数，默认是1", dataType = "int", paramType = "param")
    })
    public ResponseData<WxMpMaterialFileBatchGetResult> materialFileBatchGet(@RequestHeader String appid,
                                                                             @RequestParam(defaultValue = "image") String type,
                                                                             @RequestParam(defaultValue = "1") int page) throws WxErrorException {

        wxMpService.switchoverTo(appid);
        WxMpMaterialFileBatchGetResult res = wxAssetsService.materialFileBatchGet(type,page);
        return ResponseData.success(res);
    }

    @GetMapping("/materialNewsBatchGet")
    @ApiOperation(value = "分页获取图文素材列表", notes = "分页获取图文素材列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "appid", value = "appid", dataType = "String", paramType = "head"),
            @ApiImplicitParam(name = "page", value = "页数，默认是1", dataType = "int", paramType = "param")
    })
    public ResponseData<WxMpMaterialNewsBatchGetResult> materialNewsBatchGet(@RequestHeader String appid,
                                                                             @RequestParam(defaultValue = "1") int page) throws WxErrorException {

        wxMpService.switchoverTo(appid);
        WxMpMaterialNewsBatchGetResult res = wxAssetsService.materialNewsBatchGet(page);
        return ResponseData.success(res);
    }

    @PostMapping("/materialNewsUpload")
    @ApiOperation(value = "添加图文永久素材", notes = "添加图文永久素材")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "appid", value = "appid", dataType = "String", paramType = "head"),
            @ApiImplicitParam(name = "articles", value = "WxMpNewsArticle的集合", dataType = "List<WxMpNewsArticle>", paramType = "body")
    })
    public ResponseData<WxMpMaterialUploadResult> materialNewsUpload(@RequestHeader String appid,
                                                                     @RequestBody List<WxMpNewsArticle> articles) throws WxErrorException {

        if(articles.isEmpty())return ResponseData.error("图文列表不得为空");
        wxMpService.switchoverTo(appid);
        WxMpMaterialUploadResult res = wxAssetsService.materialNewsUpload(articles);
        return ResponseData.success(res);
    }

    @PostMapping("/materialArticleUpdate")
    @ApiOperation(value = "修改图文素材文章", notes = "修改图文素材文章")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "appid", value = "appid", dataType = "String", paramType = "head"),
            @ApiImplicitParam(name = "form", value = "WxMpMaterialArticleUpdate对象", dataType = "WxMpMaterialArticleUpdate", paramType = "body")
    })
    public ResponseData<Boolean> materialArticleUpdate(@RequestHeader String appid,@RequestBody WxMpMaterialArticleUpdate form) throws WxErrorException {

        if(form.getArticles()==null)return ResponseData.error("文章不得为空");
        wxMpService.switchoverTo(appid);
        return ResponseData.success(wxAssetsService.materialArticleUpdate(form));
    }

    @PostMapping("/materialFileUpload")
    @ApiOperation(value = "添加多媒体永久素材", notes = "添加多媒体永久素材")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "appid", value = "appid", dataType = "String", paramType = "head"),
            @ApiImplicitParam(name = "file", value = "MultipartFile文件", dataType = "MultipartFile", paramType = "body"),
            @ApiImplicitParam(name = "fileName", value = "文件名", dataType = "String", paramType = "body"),
            @ApiImplicitParam(name = "mediaType", value = "文件类型", dataType = "String", paramType = "body")
    })
    public ResponseData<WxMpMaterialUploadResult> materialFileUpload(@RequestHeader String appid,
                                                                     @RequestBody MultipartFile file,
                                                                     @RequestParam String fileName,
                                                                     @RequestParam String mediaType
    ) throws WxErrorException, IOException {

        if (file == null) return ResponseData.error("文件不得为空");
        wxMpService.switchoverTo(appid);
        WxMpMaterialUploadResult res = wxAssetsService.materialFileUpload(mediaType,fileName,file);
        return ResponseData.success(res);
    }

    @PostMapping("/materialDelete")
    @ApiOperation(value = "删除素材", notes = "删除素材")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "appid", value = "appid", dataType = "String", paramType = "head"),
            @ApiImplicitParam(name = "form", value = "MaterialFileDeleteForm", dataType = "MaterialFileDeleteForm", paramType = "body")
    })
    public ResponseData<Boolean> materialDelete(@RequestHeader String appid,@RequestBody MaterialFileDeleteForm form) throws WxErrorException {

        wxMpService.switchoverTo(appid);
        boolean res = wxAssetsService.materialDelete(form.getMediaId());
        return ResponseData.success(res);
    }

    @PostMapping("/publish")
    @ApiOperation(value = "发表图文(群发)", notes = "发表图文(群发)")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "mediaId", value = "mediaId", dataType = "String", paramType = "body")
    })
    public ResponseData<String> publish(@RequestBody String mediaId) throws WxErrorException {

        ImmutableMap<String, Object> build = ImmutableMap.<String, Object>builder()
                .put("filter", ImmutableMap.of("is_to_all", true))
                .put("mpnews", ImmutableMap.of("media_id", mediaId))
                .put("msgtype", "mpnews")
                .put("send_ignore_reprint", 0)
                .build();

        String res = wxMpService.post(MESSAGE_MASS_SENDALL_URL, JSON.toJSONString(build));
        return ResponseData.success(res);
    }

}
